package com.wjm.androidnetproclient.okhttp;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class OkHttpManager {

    private static final String TAG = "OkHttpManager";
    private static volatile OkHttpManager okHttpManager;
    private Handler handler;
    private OkHttpClient okHttpClient;

    public OkHttpManager(Context context) {
        File cacheDir = context.getCacheDir();
        int cacheSize = 10 * 1024 * 1024;
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .cache(new Cache(cacheDir.getAbsoluteFile(), cacheSize));//指定缓存目录与大小
        okHttpClient = builder.build();
        handler = new Handler();
    }

    public static OkHttpManager getInstance(Context context) {
        if (okHttpManager == null) {
            synchronized (OkHttpManager.class) {
                if (okHttpManager == null) {
                    okHttpManager = new OkHttpManager(context);
                }
            }
        }
        return okHttpManager;
    }

    public void getAsyn(String url, OkHttpCallback okHttpCallback) {
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        enqueue(call, okHttpCallback);
    }

    private void enqueue(Call call, final OkHttpCallback okHttpCallback) {
        call.enqueue(new Callback() {

            @Override
            public void onFailure(final Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        okHttpCallback.onError(call, e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        okHttpCallback.onResponse(response);

                    }
                });
            }
        });
    }
}
